<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderNumber">
        <el-input
          v-model="queryParams.orderNumber"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单类型" prop="orderType">
        <el-select v-model="queryParams.orderType" placeholder="请选择订单类型" clearable>
          <el-option
            v-for="dict in dict.type.order_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable>
          <el-option
            v-for="dict in dict.type.order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="下单时间" prop="orderCreateTime">
        <el-date-picker clearable
                        v-model="queryParams.orderCreateTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择下单时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="入库状态" prop="storeStatus">
        <el-select v-model="queryParams.storeStatus" placeholder="请选择入库状态" clearable>
          <el-option
            v-for="dict in dict.type.store_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="入库时间" prop="storeTime">
        <el-date-picker clearable
                        v-model="queryParams.storeTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择入库时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="打包状态" prop="packStatus">
        <el-select v-model="queryParams.packStatus" placeholder="请选择打包状态" clearable>
          <el-option
            v-for="dict in dict.type.pack_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="打包时间" prop="packTime">
        <el-date-picker clearable
                        v-model="queryParams.packTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择打包时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="出库状态" prop="outboundStatus">
        <el-select v-model="queryParams.outboundStatus" placeholder="请选择出库状态" clearable>
          <el-option
            v-for="dict in dict.type.outbound_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="出库时间" prop="outboundTime">
        <el-date-picker clearable
                        v-model="queryParams.outboundTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择出库时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="盘点状态" prop="stocktakingStatus">
        <el-select v-model="queryParams.stocktakingStatus" placeholder="请选择盘点状态" clearable>
          <el-option
            v-for="dict in dict.type.stocktaking_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="盘点时间" prop="stocktakingTime">
        <el-date-picker clearable
                        v-model="queryParams.stocktakingTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择盘点时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="申请寄件" prop="sendStatus">
        <el-select v-model="queryParams.sendStatus" placeholder="请选择申请寄件" clearable>
          <el-option
            v-for="dict in dict.type.send_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="寄件时间" prop="sendTime">
        <el-date-picker clearable
                        v-model="queryParams.sendTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择寄件时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="用户名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:info:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:info:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:info:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:info:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>


    <!-- 卡片展示区域 -->
    <div v-loading="loading" class="vertical-card-container">

      <!-- 垂直排列卡片列表 -->
      <div class="vertical-order-list">
        <el-card
          v-for="order in infoList"
          :key="order.id"
          class="vertical-order-card"
        >
          <!-- 卡片头部 -->
          <div slot="header" class="card-header">

            <div class="header-left">
              <!--     选择框         -->
              <!--<el-checkbox
                v-model="selectedOrders"
                :label="order.id"
                v-if="multiple"
              />-->

              <span class="order-number">
                <span class="status-label">订单编号：</span>
                {{ order.orderNumber }}
              </span>
            </div>

            <div class="header-right">
              <span class="status-label">订单状态：</span>
              <dict-tag
                :options="dict.type.order_status"
                :value="order.orderStatus"
                size="small"
              />
            </div>
          </div>

          <!-- 订单基本信息（分栏布局） -->
          <div class="vertical-base-info">
            <div class="info-grid">
              <!-- 第一列 -->
              <div class="info-column">
                <div class="info-item">
                  <label>用户名称：</label>
                  <span>{{ order.userName }}</span>
                </div>

                  <div class="info-item">
                    <label>订单类型：</label>
                    <!-- <span>{{ order.orderType }}</span> -->
                    <dict-tag :options="dict.type.order_type" :value="order.orderType"/>
                  </div>

                <div class="info-item">
                  <label>下单时间：</label>
                  <span>{{ parseTime(order.orderCreateTime) }}</span>
                </div>
                <div class="info-item">
                  <label>入库状态：</label>
                  <dict-tag :options="dict.type.store_status" :value="order.storeStatus"/>
                </div>
                <div class="info-item">
                  <label>入库时间：</label>
                  <span>{{ parseTime(order.storeTime) || '-' }}</span>
                </div>
              </div>

              <!-- 第二列 -->
              <div class="info-column">
                <div class="info-item">
                  <label>打包状态：</label>
                  <dict-tag :options="dict.type.pack_status" :value="order.packStatus"/>
                </div>
                <div class="info-item">
                  <label>打包时间：</label>
                  <span>{{ parseTime(order.packTime) || '-' }}</span>
                </div>
                <div class="info-item">
                  <label>出库状态：</label>
                  <dict-tag :options="dict.type.outbound_status" :value="order.outboundStatus"/>
                </div>
                <div class="info-item">
                  <label>出库时间：</label>
                  <span>{{ parseTime(order.outboundTime) || '-' }}</span>
                </div>
              </div>

              <!-- 第三列 -->
              <div class="info-column">
                <div class="info-item">
                  <label>盘点状态：</label>
                  <dict-tag :options="dict.type.stocktaking_status" :value="order.stocktakingStatus"/>
                </div>
                <div class="info-item">
                  <label>盘点时间：</label>
                  <span>{{ parseTime(order.stocktakingTime) || '-' }}</span>
                </div>
                <div class="info-item">
                  <label>申请寄件：</label>
                  <dict-tag :options="dict.type.send_status" :value="order.sendStatus"/>
                </div>
                <div class="info-item">
                  <label>寄件时间：</label>
                  <span>{{ parseTime(order.sendTime) || '-' }}</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 商品表格 -->
          <div class="table-container">
            <el-table
              :data="order.goodsList"
              size="mini"
              class="goods-table"
              stripe
              border
            >
              <el-table-column label="商品ID" prop="id" width="80" align="center"/>
              <el-table-column label="商品名称" prop="goodsName" width="80" align="center"/>
              <el-table-column label="快递单号" prop="trackingNumber" min-width="120" align="center"/>
              <el-table-column label="货号" prop="commSku" width="80" align="center"/>
              <el-table-column label="规格" prop="commSpec" width="80" align="center"/>
              <el-table-column label="数量" prop="quantity" width="80" align="center"/>
            </el-table>
          </div>

          <!-- 操作按钮 -->
          <div class="card-actions">
            <el-button
              type="primary"
              size="mini"
              @click="handleUpdate(order)"
              v-hasPermi="['system:info:edit']"
            >修改</el-button>
            <el-button
              type="danger"
              size="mini"
              @click="handleDelete(order)"
              v-hasPermi="['system:info:remove']"
            >删除</el-button>
          </div>
        </el-card>


        <!-- 分页组件保持原样 -->
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>



      <!-- 添加或修改订单操作对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body>
        <div class="dynamic-form">
          <!-- 表单切换内容 -->
          <transition name="el-fade-in" mode="out-in">
            <!-- 基本信息模块 -->
            <el-form
              v-if="activeTab === 'basic'"
              key="basic"
              :model="form"
              label-width="100px"
              class="form-section"
              :rules="rules"
              ref="basicForm"
            >
              <el-form-item label="订单编号" prop="orderNumber">
                <el-input v-model="form.orderNumber" placeholder="请输入订单编号" style="width: 217px"/>
              </el-form-item>
              <el-form-item label="订单类型" prop="orderType">
                <el-select v-model="form.orderType" placeholder="请选择" @change="handleOrderTypeChange">
                  <el-option
                    v-for="dict in dict.type.order_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="用户名称" prop="userName">
                <el-select v-model="form.userName" filterable placeholder="请选择" >
                  <el-option v-for="item in clientinfoselectoption" :key="item.id" :label="item.userName" :value="item.userName" >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="下单时间" prop="orderCreateTime">
                <el-date-picker
                  v-model="form.orderCreateTime"
                  type="date"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择下单时间"
                  style="width: 217px"
                />
              </el-form-item>
              <el-form-item label="订单状态">
                <el-radio-group v-model="form.orderStatus" @change="handleClientChange">
                  <el-radio
                    v-for="dict in dict.type.order_status"
                    :key="dict.value"
                    :label="parseInt(dict.value)"
                  >{{ dict.label }}</el-radio>
                </el-radio-group>
              </el-form-item>

              <!--     当订单类型下拉框触发时，就显示商品绑定         -->
              <el-divider v-if="form.showGoodsBinding">商品绑定</el-divider>

              <!--      订单类型为单件 显示 商品绑定表格  只能添加一个商品；   订单类型为组合件 显示 商品绑定表格  可以添加多个商品  ；   -->
              <template v-if="form.orderType === 0 || form.orderType === 1">
                <el-button
                  v-if="form.orderType === 1"
                  style="margin-bottom: 10px;"
                  type="primary"
                  @click="handleAddGoods">添 加</el-button>
                <el-card shadow="always" style="border-radius: 15px;">
                  <el-table :data="form.goodsList" border>
                    <el-table-column label="商品名称" width="250">
                      <template slot-scope="scope">
                        <el-select v-model="scope.row.goodsName" placeholder="请选择商品" style="width: 100%">
                          <el-option
                            v-for="item in commodselectoption"
                            :key="item.id"
                            :label="item.commName"
                            :value="item.commName">
                          </el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="数量" width="250">
                      <template slot-scope="scope">
                        <el-input-number
                          v-model="scope.row.quantity"
                          :min="1"
                          controls-position="right"
                          style="width: 100%">
                        </el-input-number>
                      </template>
                    </el-table-column>
                    <el-table-column label="快递单号" :width="form.orderType === 0 ? '300' : '250'">
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.trackingNumber" placeholder="请输入快递单号" style="width: 100%"></el-input>
                      </template>
                    </el-table-column>
                    <!-- 只在组合件模式下显示操作列 -->
                    <el-table-column
                      v-if="form.orderType === 1"
                      label="操作"
                      width="150"
                      align="center"
                      fixed="right">
                      <template slot-scope="scope">
                        <el-button
                          size="mini"
                          type="danger"
                          icon="el-icon-delete"
                          @click="handleDeleteGoods(scope.$index)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-card>
              </template>

              <!-- 调用囤货表格 -->
              <template v-if="form.orderType === 2">
                <el-button style="margin-bottom: 10px;" type="primary" @click="handleAddStock">添 加</el-button>
                <el-card shadow="always" style="border-radius: 15px;">
                  <el-table :data="form.stockList" border>
                    <el-table-column label="仓库编码" width="250">
                      <template slot-scope="scope">
                        <el-select v-model="scope.row.warehouseCode" placeholder="请选择仓库" style="width: 100%">
                          <el-option
                            v-for="item in warehouseOptions"
                            :key="item.code"
                            :label="item.name"
                            :value="item.code">
                          </el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="商品" width="250">
                      <template slot-scope="scope">
                        <el-select v-model="scope.row.goodsName" placeholder="请选择商品" style="width: 100%">
                          <el-option
                            v-for="item in commodselectoption"
                            :key="item.id"
                            :label="item.commName"
                            :value="item.commName">
                          </el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="数量" width="250">
                      <template slot-scope="scope">
                        <el-input-number
                          v-model="scope.row.quantity"
                          :min="1"
                          controls-position="right"
                          style="width: 100%">
                        </el-input-number>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="150" align="center" fixed="right">
                      <template slot-scope="scope">
                        <el-button
                          size="mini"
                          type="danger"
                          icon="el-icon-delete"
                          @click="handleDeleteStock(scope.$index)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-card>
              </template>


              <el-divider></el-divider>

            </el-form>


            <!-- 状态信息模块 -->
            <el-form
              v-else
              key="status"
              :model="form"
              label-width="100px"
              class="form-section"
              :rules="rules"
              ref="statusForm"
            >
              <el-form-item label="订单状态">
                <el-radio-group v-model="form.orderStatus">
                  <el-radio
                    v-for="dict in dict.type.order_status"
                    :key="dict.value"
                    :label="parseInt(dict.value)"
                  >{{ dict.label }}</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="入库状态" style="margin-top: 8px">
                <el-radio-group v-model="form.storeStatus">
                  <el-radio
                    v-for="dict in dict.type.store_status"
                    :key="dict.value"
                    :label="parseInt(dict.value)"
                  >
                    {{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="入库时间">
                <el-date-picker
                  v-model="form.storeTime"
                  type="date"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择入库时间"
                />
              </el-form-item>
              <el-form-item label="打包状态">
                <el-radio-group v-model="form.packStatus">
                  <el-radio
                    v-for="dict in dict.type.pack_status"
                    :key="dict.value"
                    :label="parseInt(dict.value)"
                  >
                    {{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="打包时间">
                <el-date-picker
                  v-model="form.packTime"
                  type="date"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择打包时间"
                />
              </el-form-item>

              <el-form-item label="出库状态">
                <el-radio-group v-model="form.outboundStatus">
                  <el-radio
                    v-for="dict in dict.type.outbound_status"
                    :key="dict.value"
                    :label="parseInt(dict.value)"
                  >
                    {{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="出库时间">
                <el-date-picker
                  v-model="form.outboundTime"
                  type="date"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择出库时间"
                />
              </el-form-item>

              <el-form-item label="盘点状态">
                <el-radio-group v-model="form.stocktakingStatus">
                  <el-radio
                    v-for="dict in dict.type.stocktaking_status"
                    :key="dict.value"
                    :label="parseInt(dict.value)"
                  >
                    {{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="盘点时间">
                <el-date-picker
                  v-model="form.stocktakingTime"
                  type="date"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择盘点时间"
                />
              </el-form-item>

              <el-form-item label="申请寄件">
                <el-radio-group v-model="form.sendStatus">
                  <el-radio
                    v-for="dict in dict.type.send_status"
                    :key="dict.value"
                    :label="parseInt(dict.value)"
                  >
                    {{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="寄件时间">
                <el-date-picker
                  v-model="form.sendTime"
                  type="date"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择寄件时间"
                />
              </el-form-item>
            </el-form>
          </transition>

          <!-- 切换按钮组 -->
          <div class="button-group">
            <el-button
              :type="activeTab === 'basic' ? 'primary' : 'info'"
              @click="activeTab = 'basic'"
            >订单基本信息</el-button>
            <el-button
              :type="activeTab === 'status' ? 'primary' : 'info'"
              @click="activeTab = 'status'"
            >订单状态信息</el-button>
          </div>
        </div>

        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { listInfo, getInfo, delInfo, addInfo, updateInfo } from "@/api/system/info";
import { listDetails, getDetails, delDetails, addDetails, updateDetails } from "@/api/system/details";
import {listManager} from "@/api/system/manager";
import {listCommodities} from "@/api/system/commodities";
import { addStore } from "@/api/system/store";
import {addOrderlog, updateOrderlog} from "@/api/system/orderlog";

export default {
  name: "Info",
  dicts: ['order_status', 'pack_status', 'send_status', 'order_type', 'outbound_status', 'store_status', 'stocktaking_status'],
  data() {
    return {
      selectedOrders: [],  // 选中的订单ID数组
      statusList: [  // 状态展示配置
        { label: '入库状态', prop: 'storeStatus', dictType: 'store_status', timeProp: 'storeTime' },
        { label: '打包状态', prop: 'packStatus', dictType: 'pack_status', timeProp: 'packTime' },
        { label: '出库状态', prop: 'outboundStatus', dictType: 'outbound_status', timeProp: 'outboundTime' },
        { label: '寄件状态', prop: 'sendStatus', dictType: 'send_status', timeProp: 'sendTime' }
      ],
      clientinfoselectoption: [],
      commodselectoption: [], //商品
      activeTab: 'basic', // 当前激活的标签页
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      infoList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNumber: null,
        orderType: null,
        orderStatus: null,
        orderCreateTime: null,
        storeStatus: null,
        storeTime: null,
        packStatus: null,
        packTime: null,
        outboundStatus: null,
        outboundTime: null,
        stocktakingStatus: null,
        stocktakingTime: null,
        sendStatus: null,
        sendTime: null,
        userName: null
      },
      form: {
        goodsList: [],
        stockList: [],
        showGoodsBinding: false
      },
      rules: {
        orderNumber: [
          { required: true, message: "订单编号不能为空", trigger: "blur" }
        ],
        orderType: [
          { required: true, message: "订单类型不能为空", trigger: "change" }
        ],
        orderStatus: [
          { required: true, message: "订单状态不能为空", trigger: "blur" }
        ],
        orderCreateTime: [
          { required: true, message: "下单时间不能为空", trigger: "blur" }
        ],
        storeStatus: [
          { required: true, message: "入库状态不能为空", trigger: "blur" }
        ],
        packStatus: [
          { required: true, message: "打包状态不能为空", trigger: "blur" }
        ],
        outboundStatus: [
          { required: true, message: "出库状态不能为空", trigger: "blur" }
        ],
        stocktakingStatus: [
          { required: true, message: "盘点状态不能为空", trigger: "blur" }
        ],
        sendStatus: [
          { required: true, message: "申请寄件不能为空", trigger: "blur" }
        ],
        userName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" }
        ]
      },
      goodsOptions: [],
      warehouseOptions: []
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleClientChange() {
      this.form.showGoodsBinding = true
    },
    getList() {
      this.loading = true;
      listInfo(this.queryParams).then(response => {
        // 获取订单列表
        this.infoList = response.rows;
        this.total = response.total;

        // 获取每个订单的商品明细
        const detailsPromises = this.infoList.map(order => {
          return listDetails({ orderNumber: order.orderNumber }).then(detailsRes => {
            // 将商品明细数据添加到订单对象中
            order.goodsList = detailsRes.rows.map(detail => ({
              id: detail.id,
              goodsName: detail.commName,
              trackingNumber: detail.stockTrackingnumber,
              commSku: detail.commSku,
              commSpec: detail.commSpec,
              quantity: detail.needNumber
            }));
          });
        });

        // 等待所有商品明细数据获取完成
        Promise.all(detailsPromises).finally(() => {
          this.loading = false;
        });
      });

      // 获取客户列表
      listManager().then((res) => {
        this.clientinfoselectoption = res.rows;
      });

      // 获取商品列表
      listCommodities().then((res) => {
        this.commodselectoption = res.rows;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: null,
        orderNumber: null,
        orderType: null,
        orderStatus: 1,
        orderCreateTime: null,
        storeStatus: 2,
        storeTime: null,
        packStatus: 1,
        packTime: null,
        outboundStatus: 1,
        outboundTime: null,
        stocktakingStatus: 1,
        stocktakingTime: null,
        sendStatus: 1,
        sendTime: null,
        userName: null,
        goodsList: [],
        stockList: [],
        showGoodsBinding: false
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单操作";
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getInfo(id).then(response => {
        this.form = response.data;
        if (this.form.orderType === 0 && (!this.form.goodsList || this.form.goodsList.length === 0)) {
          this.form.goodsList = [{
            goodsName: '',
            quantity: 1,
            trackingNumber: ''
          }];
        }
        this.open = true;
        this.title = "修改订单操作";
      });
    },
    submitForm() {
      const formRef = this.activeTab === 'basic' ? 'basicForm' : 'statusForm';
      this.$refs[formRef].validate(valid => {
        if (valid) {
          // 检查商品列表是否为空
          if (!this.form.goodsList || this.form.goodsList.length === 0) {
            this.$modal.msgError("请至少添加一个商品");
            return;
          }

          // 检查每个商品是否都填写完整
          for (const item of this.form.goodsList) {
            if (!item.goodsName || !item.quantity) {
              this.$modal.msgError("请完善商品信息");
              return;
            }
          }

          if (this.form.id != null) {
            // 修改订单
            updateInfo(this.form).then(response => {
              // 构建商品明细数据
              const detailsPromises = this.form.goodsList.map(item => {
                // 从commodselectoption中获取对应商品的完整信息
                const goodsInfo = this.commodselectoption.find(g => g.commName === item.goodsName);
                if (!goodsInfo) {
                  return Promise.reject("商品信息不完整");
                }

                // 构建单个商品明细数据
                const detail = {
                  orderNumber: this.form.orderNumber,
                  commName: goodsInfo.commName,
                  commSku: goodsInfo.commSku,
                  commSpec: goodsInfo.commSpec,
                  needNumber: item.quantity,
                  stockTrackingnumber: item.trackingNumber || ''
                };

                return updateDetails(detail);
              });

              // 等待所有商品明细更新完成
              Promise.all(detailsPromises).then(() => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).catch(error => {
                this.$modal.msgError(error || "修改商品明细失败");
              });
            });
          } else {
            // 新增订单
            addInfo(this.form).then(response => {
              // 构建商品明细数据
              const detailsPromises = this.form.goodsList.map(item => {
                // 从commodselectoption中获取对应商品的完整信息
                const goodsInfo = this.commodselectoption.find(g => g.commName === item.goodsName);
                if (!goodsInfo) {
                  return Promise.reject("商品信息不完整");
                }

                // 构建单个商品明细数据
                const detail = {
                  orderNumber: this.form.orderNumber,
                  commName: goodsInfo.commName,
                  commSku: goodsInfo.commSku,
                  commSpec: goodsInfo.commSpec,
                  needNumber: item.quantity,
                  stockTrackingnumber: item.trackingNumber || ''
                };

                // 同时构建入库信息数据
                const storeInfo = {
                  warehousing: 'whs' + Date.now().toString(36) + Math.random().toString(36).substr(2, 5).toUpperCase(), // 根据订单ID生成入库编号
                  orderNumber: this.form.orderNumber,
                  stockTrackingnumber: item.trackingNumber || '',
                  commName: goodsInfo.commName,
                  storeStatus: this.form.storeStatus || 2, // 使用订单中的入库状态
                  storeTime: null,//this.form.storeTime || new Date(), // 使用订单中的入库时间或当前时间
                  packageStatus: 0,//this.form.packStatus || 1, // 使用订单中的打包状态
                  loginAccount: this.$store.state.user.name, // 当前登录账号
                  orderCreateTime: this.form.orderCreateTime,
                  userAccount: this.clientinfoselectoption.find(client => client.userName === this.form.userName)?.userAccount || '', // 根据用户名查找对应的客户编号//userAccount: this.clientinfoselectoption.userAccount,//goodsInfo.userAccount || '',
                  userName: this.form.userName,
                  positionType: null, // 可根据需要设置
                  positionNumber: null // 可根据需要设置
                };

                // 添加入库信息
                addStore(storeInfo);

                return addDetails(detail);
              });

              // 等待所有商品明细添加完成
              Promise.all(detailsPromises).then(() => {

                const logForm = {
                  id: null,
                  orderNumber: this.form.orderNumber,
                  operateType: 10,
                  operateTime: null,
                  userAccount: this.$store.state.user.name,
                  userName: this.form.userName,
                  commName: null,
                  stockTrackingnumber: null
                };

                // 生成符合数据库 datetime 格式的时间字符串（本地时区，格式如 "2024-03-29 15:30:45"）
                const now = new Date();
                const year = now.getFullYear();
                const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份补零（3 → "03"）
                const day = String(now.getDate()).padStart(2, '0');
                const hours = String(now.getHours()).padStart(2, '0');
                const minutes = String(now.getMinutes()).padStart(2, '0');
                const seconds = String(now.getSeconds()).padStart(2, '0');

                logForm.operateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

                addOrderlog(logForm);

                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).catch(error => {
                this.$modal.msgError(error || "新增商品明细失败");
              });
            });
          }
        }
      });
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除订单操作编号为"' + ids + '"的数据项？').then(function() {
        return delInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleExport() {
      this.download('system/info/export', {
        ...this.queryParams
      }, `info_${new Date().getTime()}.xlsx`)
    },
    toggleTab() {
      this.activeTab = this.activeTab === 'basic' ? 'status' : 'basic'
    },
    handleAddGoods() {
      this.form.goodsList.push({
        goodsName: '',
        quantity: 1,
        trackingNumber: ''
      });
    },
    handleDeleteGoods(index) {
      this.form.goodsList.splice(index, 1);
    },
    handleAddStock() {
      this.form.stockList.push({
        warehouseCode: '',
        goodsName: '',
        quantity: 1
      });
    },
    handleDeleteStock(index) {
      this.form.stockList.splice(index, 1);
    },
    handleOrderTypeChange(value) {
      this.form.goodsList = [];
      this.form.stockList = [];

      this.form.showGoodsBinding = value !== null && value !== undefined;

      if (value === 0) {
        this.form.goodsList = [{
          goodsName: '',
          quantity: 1,
          trackingNumber: ''
        }];
      }
    }
  }
};
</script>

<style scoped>
.vertical-card-container {
  margin-top: 20px;
}

.vertical-order-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.vertical-order-card {
  width: 100%;
  margin-bottom: 16px;
  transition: all 0.3s;
}

.vertical-order-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background: #f8f9fa;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.order-number {
  font-weight: 600;
  color: #303133;
  font-size: 15px;
}

.vertical-base-info {
  padding: 16px 20px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  border-bottom: 1px solid #ebeef5;
}

.info-row {
  display: flex;
  align-items: center;
  font-size: 14px;
  line-height: 1.6;
}

.info-row label {
  color: #606266;
  min-width: 80px;
  margin-right: 16px;
  font-weight: 500;
}

.info-row span {
  color: #303133;
  flex: 1;
}

.table-container {
  padding: 0 20px;
  margin: 16px 0;
}

.goods-table {
  margin: 12px 0;
}

.goods-table ::v-deep .el-table__header th {
  background-color: #f5f7fa;
}

.status-timeline {
  padding: 16px 20px;
}

.card-actions {
  padding: 12px 20px;
  border-top: 1px solid #ebeef5;
  text-align: right;
}

@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .info-row {
    flex-wrap: wrap;
  }

  .info-row label {
    width: 100%;
    margin-bottom: 4px;
  }

  .table-container {
    overflow-x: auto;
    padding: 0;
  }

  .goods-table {
    width: 120%;
  }

  .card-actions {
    text-align: center;
  }

  .card-actions .el-button {
    width: 48%;
    margin: 0 1%;
  }
}

.header-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-label {
  color: #606266;
  font-size: 14px;
}

.vertical-base-info {
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.info-column {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.info-item label {
  color: #606266;
  font-size: 14px;
  font-weight: 500;
  min-width: 80px;
  flex-shrink: 0;
}

.info-item span {
  color: #303133;
  font-size: 14px;
  text-align: left;
}

@media (max-width: 1200px) {
  .info-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .info-grid {
    grid-template-columns: 1fr;
  }

  .info-item {
    flex-direction: row;
    flex-wrap: wrap;
  }

  .info-item label {
    width: 100%;
    margin-bottom: 4px;
  }
}

.el-input-number.is-controls-right .el-input__inner {
  padding-left: 15px;
  padding-right: 50px;
}
</style>
